<?php
/*
 * @Description    : 
 * @Author         : QianLong
 * @Date           : 2022-07-14 15:37:51
 * @LastEditors    : QianLong
 * @Site           : http://21ds.cn
 * @LastEditTime   : 2024-05-15 17:38:16
 */

namespace App\Common;

use App\Exception\ApiException;
use App\Model\AdsCate;
use App\Model\Area;
use App\Model\Manager;
use App\Model\SysSetting;
use App\Model\UserSetting;
use App\Model\Version;
use App\Service\Common;
use Yurun\Util\HttpRequest;

/**
 * Redis缓存
 */
class RedisCache
{
    public function getUserInfoByKey(string $key)
    {
        $userSettingInfo = redis()->get('dever_userInfo:dev_key:' . $key);
        $userSettingInfo = json_decode($userSettingInfo, true);
        if (!$userSettingInfo) {
            // 用户设置
            $userSettingInfo  = UserSetting::query()->where('dev_key', $key)->first();
            if (!$userSettingInfo) {
                unset($key);
                return [];
            }
            $userSettingInfo = $userSettingInfo->toArray();
            $userInfo = $this->getUserInfoById($userSettingInfo['uid']);
            $versionInfo = $this->getVersionById($userInfo['version']);
            $userSettingInfo = array_merge($userSettingInfo, $userInfo, $versionInfo);
            redis()->setex('dever_userInfo:dev_key:' . $key, config('constants.redis_expire_time'),  json_encode($userSettingInfo));
        }
        unset($key);
        return $userSettingInfo;
    }
    public function getAreaFull()
    {
        $userSettingInfo = redis()->get('dever_area:full');
        $userSettingInfo = json_decode($userSettingInfo, true);
        if (!$userSettingInfo) {
            $areaList = Area::query()->get()->toArray();
            $userSettingInfo = Common::arr2tree($areaList, 'area_id', 'parent_id', 'children');
            redis()->setex('dever_area:full', config('constants.redis_expire_time'),  json_encode($userSettingInfo));
        }
        return $userSettingInfo;
    }
    public function getUserSettingByUid($uid)
    {
        $userSettingInfo = redis()->get('dever_userSetting:uid:' . $uid);
        $userSettingInfo = json_decode($userSettingInfo, true);
        if (!$userSettingInfo) {
            // 用户设置
            $userSettingInfo  = UserSetting::query()->where('uid', $uid)->first();
            if (!$userSettingInfo) {
                unset($uid);
                return [];
            }
            $userSettingInfo = $userSettingInfo->toArray();
            redis()->setex('dever_userSetting:uid:' . $uid, config('constants.redis_expire_time'),  json_encode($userSettingInfo));
        }
        unset($key);
        return $userSettingInfo;
    }
    public function setFilterEmail(string $filter_id, string $email)
    {
        if (empty($email)) {
            return false;
        } else {
            $result = redis()->sAdd('dever_email:filter:' . $filter_id, $email);
            redis()->expire('dever_email:filter:' . $filter_id, config('constants.redis_expire_time') * 7);
            return $result;
        }
    }
    public function setFilterPhone(string $filter_id, string $phone)
    {
        if (empty($phone)) {
            return false;
        } else {
            $result = redis()->sAdd('dever_sms:filter:' . $filter_id, $phone);
            redis()->expire('dever_sms:filter:' . $filter_id, config('constants.redis_expire_time') * 7);
            return $result;
        }
    }
    public function setFilterCid(string $filter_id, string $cid)
    {
        if (empty($cid)) {
            return false;
        } else {
            $result = redis()->sAdd('dever_push:filter:' . $filter_id, $cid);
            redis()->expire('dever_push:filter:' . $filter_id, config('constants.redis_expire_time') * 7);
            return $result;
        }
    }
    public function getSysSetting()
    {
        $userSettingInfo = redis()->get('dever_sys:setting');
        $userSettingInfo = json_decode($userSettingInfo, true);
        if (!$userSettingInfo) {
            // 用户设置
            $userSettingInfo  = SysSetting::query()->where('id', 1)->first();
            if (!$userSettingInfo) {
                unset($key);
                return [];
            }
            $userSettingInfo = $userSettingInfo->toArray();
            redis()->setex('dever_sys:setting', config('constants.redis_expire_time'),  json_encode($userSettingInfo));
        }
        unset($key);
        return $userSettingInfo;
    }
    // 删除集合中指定的元素值
    public function deleteSocketMember(string $key, $fd)
    {
        return redis()->sRem('dever_socket:fd:' . $key, $fd);
    }
    public function setSocketMember(string $key, $fd)
    {
        $memberList = redis()->sMembers('dever_socket:fd:' . $key);
        unset($key);
        if (in_array($fd, $memberList)) {
            redis()->sAdd('dever_socket:fd:' . $key, $fd);
            redis()->expire('dever_socket:fd:' . $key, 7200);
        } else {
            redis()->sAdd('dever_socket:fd:' . $key, $fd);
            redis()->expire('dever_socket:fd:' . $key, 7200);
        }
    }
    public function getUserInfoById($uid)
    {
        $uid = intval($uid);
        $userSettingInfo = redis()->get('dever_userInfo:uid:' . $uid);
        $userSettingInfo = json_decode($userSettingInfo, true);
        if (!$userSettingInfo) {
            // 用户设置
            $userSettingInfo  = Manager::query()->where('id', $uid)->first();
            if (!$userSettingInfo) {
                unset($key);
                return [];
            }
            $userSettingInfo = $userSettingInfo->toArray();
            redis()->setex('dever_userInfo:uid:' . $uid, config('constants.redis_expire_time'),  json_encode($userSettingInfo));
        }
        unset($key);
        return $userSettingInfo;
    }
    public function getPushSpiderLimit($key)
    {
        $userSettingInfo = redis()->get('dever_push_spider:key:' . $key);
        if (empty($userSettingInfo)) {
            redis()->setex('dever_push_spider:key:' . $key, 86400*3,  1);
            return true;
        }
        unset($key);
        return false;
    }
    public function getAdsCate($id)
    {
        $userSettingInfo = redis()->get('dever_ads:cate:' . $id);
        $userSettingInfo = json_decode($userSettingInfo, true);
        if (!$userSettingInfo) {
            // 用户设置
            $userSettingInfo  = AdsCate::query()->where('id_var', $id)->first();
            if (!$userSettingInfo) {
                unset($key);
                return [];
            }
            $userSettingInfo = $userSettingInfo->toArray();
            redis()->setex('dever_ads:cate:' . $id, config('constants.redis_expire_time'),  json_encode($userSettingInfo));
        }
        unset($key);
        if (empty($userSettingInfo)) {
            throw new ApiException('广告分类不存在或已删除');
        }
        return $userSettingInfo;
    }
    public function getVersionById($vid)
    {
        $userSettingInfo = redis()->get('dever_versionInfo:id:' . $vid);
        $userSettingInfo = json_decode($userSettingInfo, true);
        if (!$userSettingInfo) {
            // 用户设置
            $userSettingInfo  = Version::query()->where('id', $vid)->first();
            if (!$userSettingInfo) {
                unset($key);
                return [];
            }
            $userSettingInfo = $userSettingInfo->toArray();
            redis()->setex('dever_versionInfo:id:' . $vid, config('constants.redis_expire_time'),  json_encode($userSettingInfo));
        }
        unset($key);
        return $userSettingInfo;
    }
    public function isNewUv(string $ip, string $s_id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever_ip:' . $ip . ':' . $s_id);
        if ($cacheTTL === -1 || $cacheTTL > 86400) {
            redis()->del('dever_ip:' . $ip . ':' . $s_id);
        }
        unset($cacheTTL);
        $Info = redis()->get('dever_ip:' . $ip . ':' . $s_id);
        if (empty($Info)) {
            $expire = strtotime(date('Y-m-d')) + 86400 - time();
            redis()->setex('dever_ip:' . $ip . ':' . $s_id, $expire, $ip);
            return true;
        }
        return false;
    }
    public function sendLimit(string $field, string $type)
    {
        switch ($type) {
            case 'minute':
                $expire = 60;
                break;
            case 'hour':
                $expire = 3600;
                break;
            case 'day':
                $time = time();
                $tomorrow = strtotime(date('Y-m-d') . ' +1 day');
                $expire = $tomorrow - $time;
                break;
            default:
                $expire = 0;
                break;
        }
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever_send:' . $type . ':limit:' . $field);
        if ($cacheTTL === -1 || $cacheTTL > 86401) {
            redis()->del('dever_send:' . $type . ':limit:' . $field);
        }
        unset($cacheTTL);
        $count = redis()->get('dever_send:' . $type . ':limit:' . $field);
        if (empty($count)) {
            $count = 1;
            redis()->setex('dever_send:' . $type . ':limit:' . $field, $expire, $count);
        } else {
            redis()->incr('dever_send:' . $type . ':limit:' . $field);
            $count = redis()->get('dever_send:' . $type . ':limit:' . $field);
        }
        return $count;
    }
    public function silentLimit($params, $silent)
    {
        unset($params['sign']);
        $paramsMd5 = md5(json_encode($params));
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('lib:push:silent:' . $paramsMd5);
        if ($cacheTTL === -1 || $cacheTTL > $silent) {
            redis()->del('lib:push:silent:' . $paramsMd5);
        }
        unset($cacheTTL);
        $count = redis()->get('lib:push:silent:' . $paramsMd5);
        if (empty($count)) {
            $count = 1;
            redis()->setex('lib:push:silent:' . $paramsMd5, $silent, $count);
        } else {
            throw new ApiException(-1, '静默期，不处理');
        }
    }
    public function sendLimitDec(string $field, string $type)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever_send:' . $type . ':limit:' . $field);
        if ($cacheTTL === -1 || $cacheTTL > 86401) {
            redis()->del('dever_send:' . $type . ':limit:' . $field);
        }
        unset($cacheTTL);
        $count = redis()->get('dever_send:' . $type . ':limit:' . $field);
        if (!empty($count)) {
            redis()->decr('dever_send:' . $type . ':limit:' . $field);
        }
    }
    /**
     * 查询邮件模板
     */
    public function getEmailTemplateRealTime(string $id): string
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:email:template:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:email:template:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:email:template:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->email_tpl_list->findOne(['_id' => $id, 'status' => 1]);
            $result = json_decode(json_encode($result), true);
            if (!empty($result)) {
                $content = $result['tpl'];
                redis()->setex('dever:email:template:' . $id, config('constants.redis_expire_time'),  $content);
            }
            unset($result);
        }
        return $content;
    }
    public function getXfFileIds(string $ws_id,$uid)
    {
        $fileIds = [];
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:xf:file_ids:' . $ws_id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:xf:file_ids:' . $ws_id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:xf:file_ids:' . $ws_id);
        if (empty($content)) {
            $where['_id'] = $ws_id;
            $where['uid'] = (int)$uid;
            $hasLog = mongodb2()->xf_file_list->find($where);
            foreach ($hasLog as $key => $vo) {
                $fileIds[] = $vo['file_id'];
            }
            redis()->setex('dever:xf:file_ids:' . $ws_id, config('constants.redis_expire_time'),  implode(',', $fileIds));
            unset($result);
        }else{
            $fileIds = explode(',', $content);
        }
        return $fileIds;
    }
    public function getEmailSetting($uid)
    {
        $uid = (int) $uid;
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:email:setting:' . $uid);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time') + 1) {
            redis()->del('dever:email:setting:' . $uid);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:email:setting:' . $uid);
        if (empty($content)) {
            // 模板信息
            $content = mongodb2()->send_email_setting->findOne(['uid' => $uid]);
            $content = json_encode($content);
            redis()->setex('dever:email:setting:' . $uid, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getEmailServer(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:email:server:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:email:server:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:email:server:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->email_server_list->findOne(['_id' => $id]);
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:email:server:' . $id, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getWsServer(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:socket.io:server:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:socket.io:server:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:socket.io:server:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->socket_io->findOne(['_id' => $id]);
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:socket.io:server:' . $id, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getAppInfo(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:app:info:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:app:info:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:app:info:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->app_list->findOne(['_id' => $id]);
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:app:info:' . $id, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getAk(string $id,$uid)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:ak:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:ak:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:ak:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->ak_list->findOne(['_id' => $id,'uid'=>(int)$uid]);
            if (empty($result)) {
                throw new ApiException(-1, 'AK凭证不存在');
            }
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:ak:' . $id, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getLogSite(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:log:site:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:log:site:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:log:site:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->log_site_list->findOne(['_id' => $id]);
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:log:site:' . $id, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getFeedbackSite(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:feedback:site:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:feedback:site:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:feedback:site:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->feedback_site_list->findOne(['_id' => $id]);
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:feedback:site:' . $id, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getMpWxInfo($mw_id)
    {
        $tag = substr($mw_id,0,2);
        if (strtolower($tag) == 'mw') {
            $where['_id'] = $mw_id;
        }else{
            $where['app_id'] = $mw_id;
        }
        $infoData = mongodb2()->mp_weixin->findOne($where);
        $infoData = json_decode(json_encode($infoData), true);
        if (empty($infoData)) {
            throw new ApiException(-1, '对应公众号不存在');
        }
        $infoData['event_url'] = isset($infoData['event_url'])? $infoData['event_url']:'';
        return $infoData;
    }
    public function getMxAppInfo($ma_id)
    {
        $tag = substr($ma_id,0,2);
        if (strtolower($tag) == 'wa') {
            $where['_id'] = $ma_id;
        }else{
            $where['app_id'] = $ma_id;
        }
        $infoData = mongodb2()->mp_miniapp->findOne($where);
        $infoData = json_decode(json_encode($infoData), true);
        if (empty($infoData)) {
            throw new ApiException(-1, '对应小程序不存在');
        }
        return $infoData;
    }
    public function getWxWorkInfo($ww_id)
    {
        $where['$or'] = [];
        $where['$or'][] = ['_id' => $ww_id];
        $where['$or'][] = ['crop_id' => $ww_id];
        $infoData = mongodb2()->mp_work->findOne($where);
        $infoData = json_decode(json_encode($infoData), true);
        if (empty($infoData)) {
            throw new ApiException(-1, '企业微信不存在');
        }
        return $infoData;
    }
    public function getNeedSecUser($user,$content='')
    {
        $cacheTTL = redis()->ttl('dever:mp_keyword:sec:' . $user);
        if ($cacheTTL === -1 || $cacheTTL > 120) {
            redis()->del('dever:mp_keyword:sec:' . $user);
        }
        unset($cacheTTL);
        if (!empty($content)) {
            redis()->setex('dever:mp_keyword:sec:' . $user, 120,  $content);
        }else{
            $content = redis()->get('dever:mp_keyword:sec:' . $user);
        }
        return $content;
    }
    /**
     * 查询短信模板
     */
    public function getSmsTemplateRealTime(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:sms:template:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:sms:template:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:sms:template:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->sms_tpl_list->findOne(['_id' => $id, 'status' => 1]);
            if (!empty($result)) {
                $content = json_encode($result);
                redis()->setex('dever:sms:template:' . $id, config('constants.redis_expire_time'),  $content);
            }
            unset($result);
        }
        return json_decode($content, true);
    }
    public function getSmsSetting($uid)
    {
        $uid = (int) $uid;
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:sms:setting:' . $uid);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time') + 1) {
            redis()->del('dever:sms:setting:' . $uid);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:sms:setting:' . $uid);
        if (empty($content)) {
            // 模板信息
            $content = mongodb2()->send_sms_setting->findOne(['uid' => $uid]);
            $content = json_encode($content);
            redis()->setex('dever:sms:setting:' . $uid, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getSmsServer(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:sms:server:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:sms:server:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:sms:server:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->sms_server_list->findOne(['_id' => $id]);
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:sms:server:' . $id, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    /**
     * 查询推送模板
     */
    public function getPushTemplateRealTime(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:push:template:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:push:template:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:push:template:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->push_tpl_list->findOne(['_id' => $id, 'status' => 1]);
            if (!empty($result)) {
                $content = json_encode($result);
                redis()->setex('dever:push:template:' . $id, config('constants.redis_expire_time'),  $content);
            }
            unset($result);
        }
        return json_decode($content, true);
    }
    public function getPushSetting($uid)
    {
        $uid = (int) $uid;
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:push:setting:' . $uid);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time') + 1) {
            redis()->del('dever:push:setting:' . $uid);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:push:setting:' . $uid);
        if (empty($content)) {
            // 模板信息
            $content = mongodb2()->send_push_setting->findOne(['uid' => $uid]);
            $content = json_encode($content);
            redis()->setex('dever:push:setting:' . $uid, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getPushServer(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:push:server:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:push:server:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:push:server:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->push_server_list->findOne(['_id' => $id]);
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:push:server:' . $id, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getPushServerByKey(string $key)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:push:server:' . $key);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:push:server:' . $key);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:push:server:' . $key);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->push_server_list->findOne(['hook_key' => $key]);
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:push:server:' . $key, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getFileSetting($uid)
    {
        $uid = (int) $uid;
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:file:setting:' . $uid);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time') + 1) {
            redis()->del('dever:file:setting:' . $uid);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:file:setting:' . $uid);
        if (empty($content)) {
            // 模板信息
            $content = mongodb2()->send_file_setting->findOne(['uid' => $uid]);
            $content = json_encode($content);
            redis()->setex('dever:file:setting:' . $uid, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getFileServer(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:file:server:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:file:server:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:file:server:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->file_server_list->findOne(['_id' => $id]);
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:file:server:' . $id, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    public function getFileCate(string $id)
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $cacheTTL = redis()->ttl('dever:file:cate:' . $id);
        if ($cacheTTL === -1 || $cacheTTL > config('constants.redis_expire_time')) {
            redis()->del('dever:file:cate:' . $id);
        }
        unset($cacheTTL);
        $content = redis()->get('dever:file:cate:' . $id);
        if (empty($content)) {
            // 模板信息
            $result = mongodb2()->file_cate->findOne(['_id' => $id]);
            $content = json_encode($result, true);
            unset($result);
            redis()->setex('dever:file:cate:' . $id, config('constants.redis_expire_time'),  $content);
        }
        return json_decode($content, true);
    }
    // 获取accessToken
    public function getWechatAccessToken($app_id, $app_secret)
    {
        $cacheTTL = redis()->ttl('dever_access_token:' . $app_id);
        if ($cacheTTL === -1 || $cacheTTL > 7200) {
            redis()->del('dever_access_token:' . $app_id);
        }
        unset($cacheTTL);
        $Info = redis()->get('dever_access_token:' . $app_id);
        if (empty($Info)) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $app_id . '&secret=' . $app_secret;
            $http = new HttpRequest;
            $response = $http->get($url);
            $responseArr = json_decode($response->body(), true);
            if (isset($responseArr['errcode']) && $responseArr['errcode'] != 0) {
                throw new ApiException(-1, $responseArr['errmsg']);
            }
            if (!isset($responseArr['expires_in']) || !isset($responseArr['access_token'])) {
                throw new ApiException(-1, 'access_token获取失败');
            }
            $Info = $responseArr['access_token'];
            redis()->setex('dever_access_token:' . $app_id, $responseArr['expires_in'] - 300, $Info);
        }
        return $Info;
    }
    public function getWxAppAccessToken($app_id, $app_secret)
    {
        $cacheTTL = redis()->ttl('dever_wxapp_access_token:' . $app_id);
        if ($cacheTTL === -1 || $cacheTTL > 7200) {
            redis()->del('dever_wxapp_access_token:' . $app_id);
        }
        unset($cacheTTL);
        $Info = redis()->get('dever_wxapp_access_token:' . $app_id);
        if (empty($Info)) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $app_id . '&secret=' . $app_secret;
            $http = new HttpRequest;
            $response = $http->get($url);
            $responseArr = json_decode($response->body(), true);
            if (isset($responseArr['errcode']) && $responseArr['errcode'] != 0) {
                throw new ApiException(-1, $responseArr['errmsg']);
            }
            if (!isset($responseArr['expires_in']) || !isset($responseArr['access_token'])) {
                throw new ApiException(-1, 'access_token获取失败');
            }
            $Info = $responseArr['access_token'];
            redis()->setex('dever_wxapp_access_token:' . $app_id, $responseArr['expires_in'] - 300, $Info);
        }
        return $Info;
    }
    public function getWxWorkAccessToken($crop_id,$agent_id, $app_secret)
    {
        $cacheTTL = redis()->ttl('dever_wx_work_access_token:' . $crop_id.':'. $agent_id);
        if ($cacheTTL === -1 || $cacheTTL > 7200) {
            redis()->del('dever_wx_work_access_token:' . $crop_id . ':' . $agent_id);
        }
        unset($cacheTTL);
        $Info = redis()->get('dever_wx_work_access_token:' . $crop_id . ':' . $agent_id);
        if (empty($Info)) {
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='. $crop_id.'&corpsecret='. $app_secret;
            $http = new HttpRequest;
            $response = $http->get($url);
            $responseArr = json_decode($response->body(), true);
            if (isset($responseArr['errcode']) && $responseArr['errcode'] != 0) {
                throw new ApiException(-1, $responseArr['errmsg']);
            }
            if (!isset($responseArr['expires_in']) || !isset($responseArr['access_token'])) {
                throw new ApiException(-1, 'access_token获取失败');
            }
            $Info = $responseArr['access_token'];
            redis()->setex('dever_wx_work_access_token:' . $crop_id . ':' . $agent_id, $responseArr['expires_in'] - 300, $Info);
        }
        return $Info;
    }
    /**
     * 读取和设置个推送token数据
     */
    public function getSetAuthToken($ps_id, string $appid, ?string $sign = null, int $time = 86300)
    {
        if (empty($sign)) {
            return redis()->get('dever:push:' . $ps_id . ':getui:' . $appid);
        } else {
            redis()->setex('dever:push:' . $ps_id . ':getui:' . $appid, $time, $sign);
        }
    }
    public function getSetMongodbIndex($name, ?string $data = null, int $time = 604800)
    {
        if (empty($data)) {
            return redis()->get('dever:mongodb:index:' . $name);
        } else {
            redis()->setex('dever:mongodb:index:' . $name, $time, $data);
        }
    }
    public function getSetSocketUnionId($name, $data = null, int $time = 604800)
    {
        if (empty($data)) {
            return redis()->get('dever:socket_unionid:' . $name);
        } else {
            redis()->setex('dever:socket_unionid:' . $name, $time, $data);
        }
    }
    public function getSetMpOauthParam($id, ?string $data = null, int $time = 3600)
    {
        if (empty($data)) {
            return redis()->get('dever:mp_weixin:oauth:' . $id);
        } else {
            redis()->setex('dever:mp_weixin:oauth:' . $id, $time, $data);
        }
    }
}
